package com.sxg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxg.config.security.context.AuthenticationContextHolder;
import com.sxg.constant.CacheConstants;
import com.sxg.constant.Constants;
import com.sxg.entity.SxgUserEntity;
import com.sxg.exception.ServerException;
import com.sxg.redis.RedisCache;
import com.sxg.security.pojo.LoginUser;
import com.sxg.security.service.TokenService;
import com.sxg.service.SxgUserService;
import com.sxg.utils.MessageUtils;
import com.sxg.utils.SecurityUtils;
import com.sxg.utils.StringUtils;
import com.sxg.utils.code.AjaxResult;
import com.sxg.vo.req.RegisterReqVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SxgLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SxgUserService sxgUserService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        try {
            username = username.substring(0, username.indexOf("@"));
        } catch (Exception e) {
            throw new RuntimeException("邮箱格式错误");
        }
        // 验证码校验
//        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new RuntimeException("密码错误");
            } else {
                throw new ServerException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new RuntimeException(MessageUtils.message("user.jcaptcha.expire"));
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new RuntimeException(MessageUtils.message("user.jcaptcha.error"));
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new RuntimeException(MessageUtils.message("user.not.null"));
        }
        // 密码如果不在指定范围内 错误
//        if (password.length() < 5
//                || password.length() > 20) {
//            throw new RuntimeException(MessageUtils.message("user.password.not.match"));
//        }
        // 用户名不在指定范围内 错误
        if (username.length() < 2
                || username.length() > 20) {
            throw new RuntimeException(MessageUtils.message("user.username.not.match"));
        }
    }

    public AjaxResult register(RegisterReqVo vo) {
        String qq = null;
        try {
            qq = vo.getEmail().substring(0, vo.getEmail().indexOf("@"));
        } catch (Exception e) {
            return AjaxResult.error("邮箱格式错误");
        }

        Long username = null;
        try {
            username = Long.valueOf(qq);
        } catch (NumberFormatException e) {
            return AjaxResult.error("目前只支持前缀为数字的邮箱，例如qq邮箱");
        }

        Object object = redisCache.getCacheObject(CacheConstants.MAIL_CODE_KEY + qq);
        if (object == null) {
            return AjaxResult.error("验证码已过期");
        }

        if (!object.equals(vo.getCode())) {
            return AjaxResult.error("验证码错误");
        }

        if (StringUtils.isNotEmpty(qq)) {
            SxgUserEntity user = sxgUserService.getOne(new QueryWrapper<SxgUserEntity>().select("user_name").eq("user_name", qq));
            if (StringUtils.isNotNull(user)) {
                return AjaxResult.error("该账户已注册");
            }
        }

        redisCache.deleteObject(CacheConstants.MAIL_CODE_KEY + qq);

        // 注册用户信息
        SxgUserEntity user = new SxgUserEntity();
        user.setUserName(username);
        user.setNickName(vo.getEmail());
        user.setEmail(vo.getEmail());
        user.setPassword(SecurityUtils.encryptPassword(vo.getPassword()));
        user.setGender("2");
        user.setStatus("0");
        sxgUserService.save(user);
        return AjaxResult.success();
    }

    public AjaxResult logout(HttpServletRequest request) {
        try {
            tokenService.delete(request);
        } catch (Exception e) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }


}
